package com.xingchen.loveparttimejob.uitls;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingchen.loveparttimejob.Main;
import com.xingchen.loveparttimejob.model.pojo.JobInfoText;

import java.io.IOException;

/**
 * @author 小志
 * @date 2024/11/29 - 8:35
 */
public class JSONUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 对象转换成JSON字符串
     * @param obj 要转换对象
     * @param tClass 对象类型
     * @return 返回转换的JSON字符串
     * @param <T>  转换的对象类型
     */
    public static <T> String getObjectJson(T obj,Class<T> tClass){
        String json = "";
        try {
            json = OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * JSON字符串转换成对象
     * @param jsonStr 要转换的JSON字符串
     * @param tClass 要转换成的对像
     * @return 转换成的对象
     * @param <T> 转换的对象
     */
    public static <T> T getJsonObject(String jsonStr,Class<T> tClass){
        T json = null;
        try {
            json = OBJECT_MAPPER.readValue(jsonStr,tClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * 获取我们默认显示的文本
     * @param name 名称
     * @return JobInfoText对象
     */
    public static JobInfoText getJobInfoDefaultText(String name){
        JobInfoText jobInfoText = new JobInfoText();
        try {
            JsonNode rootNode = OBJECT_MAPPER.readTree(Main.class.getClassLoader().getResourceAsStream("JobInfoText.JSON"));
            for (JsonNode node : rootNode) {
                if (node.has("name") && name.equals(node.get("name").asText())) {
                    jobInfoText = new JobInfoText(node.get("name").asText(),node.get("title").asText(),node.get("content").asText());
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jobInfoText;
    }
}
